<template>
    <div>
      <el-form :model="condition" size="small" :inline="true">
        <el-form-item label="角色名称">
          <el-input v-model="condition.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-select v-model="condition.enableStatus" placeholder="请选择启用状态" clearable>
            <el-option v-for="(s,index) in stateArr" :key="index" :label="s" :value="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button icon="el-icon-refresh-left" @click="reset()">重置</el-button>
          <el-button icon="el-icon-circle-plus-outline" @click="showRoleDialog()">新增</el-button>
        </el-form-item>
      </el-form>
      <div style="height: 34px">
        <el-pagination background align="right" v-show="total > 0"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="currentPage"
                       :page-sizes="pageSizes"
                       :page-size="pageSize"
                       layout="total, sizes, prev, pager, next"
                       :total="total">
        </el-pagination>
      </div>
      <!-- el-table的data属性就是用来绑定这个表格显示的数据 -->
      <el-table :data="roles" height="100%" style="width: 100%">
        <!-- el-table-column表示表格的每一列信息 label属性表示表头的名称
           prop表示绑定的字段名 width属性表示这一列显示的宽度-->
        <el-table-column prop="id" label="角色编号"/>
        <el-table-column prop="name" label="角色名称"/>
        <el-table-column prop="enableStatus" label="启用状态">
            <template slot-scope="scope">
            <span v-if="scope.row.enableStatus === 0">未启用</span>
            <span v-else>已启用</span>
          </template>
        </el-table-column>
        <el-table-column prop="enName" label="英文名称"/>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="showRoleDialog(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.enableStatus === 0" type="text" @click="changeFrozenState(scope.row.id, 0, 1)">启用</el-button>
            <el-button v-else type="text" @click="changeFrozenState(scope.row.id,1, 0)">停用</el-button>
            <el-button type="text" @click="deleteUser(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="编辑角色信息" :visible.sync="roleDialog.visible" width="50%">
        <el-form :model="roleDialog.editRole" :rules="roleDialog.roleRules" ref="roleForm" :inline="true">
          <!-- <el-form-item label="角色编号">
            <el-input v-model="roleDialog.editRole.id" readonly/>
          </el-form-item> -->
          <el-form-item label="角色名称">
            <el-input v-model="roleDialog.editRole.name" placeholder="请输入名称" clearable />
          </el-form-item>
          <el-form-item prop="sex" label="启用状态">
            <el-select v-model="roleDialog.editRole.enableStatus" placeholder="请选择启用状态" clearable>
              <el-option v-for="(s,index) in stateArr" :key="index" :label="s" :value="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="age" label="英文名称">
            <el-input v-model="roleDialog.editRole.enName" placeholder="请输入英文名称" clearable />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  export default {
    name: "Role",
    data(){
      return {
        condition: {
          name: '',
          enableStatus: ''
        },
        stateArr: ['未启用', '已启用'],
        roles: [],
        currentPage: 1, //分页的默认页码应该是第一页
        pageSizes: [5, 10, 15, 20, 40], //可选的每页显示条数
        pageSize: 5, //每页显示条数
        total: 0, //查询的总条数，默认值为0，查询之后才会赋值
        roleDialog: {
          visible: false,
          isUpdate: false,
          editRole: {
            id: '',
            name: '',
            enableStatus: '',
            enName: ''
          },
          roleRules: {
            name: [
              {required: true, message: '角色名称不能为空', trigger: ['blur', 'change']}
            ],
            enableStatus: [
              {required: true, message: '启用状态不能为空', trigger: ['blur', 'change']}
            ]
          }
        }
      }
    },
    methods: {
      handleSizeChange(val){//这个函数是用来监听每页显示条数的变更
        this.currentPage = 1
        this.pageSize = val
        this.search()
      },
      handleCurrentChange(val){//这个函数是用来监听当前页码变化
        this.currentPage = val
        this.search()
      },
      search(){
        this.doGet('/role', {
          name: this.condition.name,
          enableStatus: this.condition.enableStatus,
          currentPage: this.currentPage,
          pageSize: this.pageSize
        }, resp => {
          this.roles = resp.records
          this.total = resp.total
        })
      },
      showRoleDialog(role){
        if(role==null){//是新增
            this.roleDialog.isUpdate=false;
        }else{//是编辑
            this.roleDialog.isUpdate=true;
            //首先获取role对象的属性集合，然后遍历这个集合，将每一个属性值拷贝到editRole对象中
            Object.keys(role).forEach(key => this.roleDialog.editRole[key] = role[key])
        }
       
        this.roleDialog.visible = true
      },
      closeDialog(){
        this.roleDialog.visible = false
        this.roleDialog.editRole = {
          id: '',
          name: '',
          enableStatus: '',
          enName: ''
        }
        //重置所有的表单验证，这样可以清除提示信息
        this.$refs['roleForm'].resetFields();
      },
      save(){
        console.log("this.roleDialog.isUpdate="+this.roleDialog.isUpdate);
        this.$refs['roleForm'].validate(valid => {
        if(valid){

            // 编辑
          if(this.roleDialog.isUpdate){
            //这里就可以提交信息去后台服务器保存数据
            this.doPut('/role', this.roleDialog.editRole, resp => {
              if(resp){
                this.$message.success("保存成功")
                this.closeDialog()
                this.search()
              } else {
                this.$message.error("角色编号或序号已存在")
              }
            })
          } else {

            // 新增
            this.doPost('/role', this.roleDialog.editRole, resp => {
              if(resp){
                this.$message.success("保存成功")
                this.closeDialog()
                this.search()
              } else {
                this.$message.error("角色编号或序号已存在")
              }
            })
          }
        } else {
          return false
        }
      })
    },
    //   save(){
    //     this.$refs['roleForm'].validate(valid => {
    //       if(valid){
    //         //这里就可以提交信息去后台服务器保存数据
    //         this.doPut('/role', this.roleDialog.editRole, resp => {
    //           if(resp){
    //              this.$message.success("保存成功")
    //              this.closeDialog()
    //              this.search()
    //           } else {
    //              this.$message.error("保存失败")
    //           }     
    //         })
    //       } else {
    //         return false
    //       }
    //     })
    //   },
      deleteUser(role){
        this.showConfirm(`确定要删除角色${role.name}吗?`, () => {
          //点击确定按钮后才会执行删除动作
          this.doDelete(`/role/${role.id}`, this.id, resp  => {
             if(resp){
               this.$message.success("删除成功")
               this.search()
             } else {
               this.$message.error("删除失败")
             }
          })
        })
      },
      reset(){
        this. condition = {
          name: '',
          enableStatus: ''
        }
        this.search()
      },
      changeFrozenState(id, oldState, newState){
        this.doPut('/role/state', {
          id: id,
          oldState: oldState,
          newState: newState
        }, resp => {
          if(resp){
            this.$message.success(`${newState === 0 ? '冻结': '解冻'}成功`)
            this.search()
          } else {
            this.$message.error(`${newState === 0 ? '冻结': '解冻'}失败`)
          }
        })
      }
    },
    mounted() { //这个函数是一个钩子函数，有vue自动调用，在页面完成挂载之后就会调用这个函数
      this.search()
    }
  }
  </script>
  
  <style scoped>
  
  </style>
  